package com.zhengdongzulin.zuke.app.main.mine.bill

import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseNodeAdapter
import com.chad.library.adapter.base.entity.node.BaseNode
import com.chad.library.adapter.base.provider.BaseNodeProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lihang.ShadowLayout
import com.lxj.androidktx.core.getVM
import com.lxj.androidktx.core.toast
import com.zhengdongzulin.zuke.R
import com.zhengdongzulin.zuke.app.data.Bill
import com.zhengdongzulin.zuke.app.data.Bill1
import com.zhengdongzulin.zuke.app.data.BillData
import com.zhengdongzulin.zuke.base.BaseFragment
import com.zhengdongzulin.zuke.databinding.ZkFragmentBillBinding
import com.zhengdongzulin.zuke.ext.setDrawRight

import net.lucode.hackware.magicindicator.buildins.UIUtil

/**
 * 账单
 */
class ZKBillFragment(var mType: BillType) : BaseFragment<BillVm, ZkFragmentBillBinding>() {

    enum class BillType {
        UNPAID_BILL,
        HISTORY_BILL
    }

    private var mTotalMoney = 0.00
    private var mData: MutableList<Bill> = mutableListOf()
    var mDeptListShowAdapter: DeptListShowAdapter? = null
    var mNodeBaseAdapter: NodeBaseAdapter? = null
    var mNodeAdapter: NodeAdapter? = null


    companion object {
        fun newInstance(type: BillType) = ZKBillFragment(type)
    }


    override fun getLayoutResId(): Int = R.layout.zk_fragment_bill

    override fun initVM(): BillVm = getVM(BillVm::class.java)

    override fun initView() {
        mView.contentView.setEnableRefresh(false)
        mView.statusView.showLoading()
        mNodeBaseAdapter = NodeBaseAdapter()
        mNodeAdapter = NodeAdapter()
        mDeptListShowAdapter = DeptListShowAdapter()
        mDeptListShowAdapter!!.setList(mData)
        mView.recyclerView.layoutManager = LinearLayoutManager(context)
        mView.recyclerView.adapter = mDeptListShowAdapter
        mView.clBottomOperation.visibility =
            if (mType == BillType.UNPAID_BILL) View.VISIBLE else View.GONE
    }

    override fun initData() {
        resetTotalMoney()
        getData()
    }

    override fun initListener() {
        mView.tvPay.setOnClickListener {
            pay()
        }
    }

    private fun getData() {
        mView.statusView.showLoading()
        mViewModel.bill_list(
            (activity as ZKBillActivity).mChangeHomeData.houseId,
            if (mType == BillType.UNPAID_BILL) "1" else "2"
        )
//        for (i in 0..5){
//            var childList : MutableList<BaseNode> = mutableListOf()
//            for (j in 0..3){
//                var bill1 = Bill1(
//                        "$j",
//                        "退房",
//                        "2021-06-0$j",
//                        "2021-06-0$j",
//                        "2021-06-0$j",
//                        "1",
//                        (j * 1000).toString(),
//                "11")
//                childList.add(bill1)
//            }
//            var bill = Bill("2021-06-0$i", childList)
//            mData.add(bill)
//        }


    }

    override fun startObserve() {
        mViewModel.bill_list.observe(this, androidx.lifecycle.Observer {
            processingData(it)
        })
        mViewModel.bill_list.state.observe(this, getObserver(mViewModel.bill_list))
    }

    inner class DeptListShowAdapter : BaseNodeAdapter() {
        override fun getItemType(data: List<BaseNode>, position: Int): Int {
            return if (data[position] is Bill) {
                0
            } else {
                1
            }
        }

        init {
            addFullSpanNodeProvider(mNodeBaseAdapter!!)
            addFullSpanNodeProvider(mNodeAdapter!!)
//            addNodeProvider(NodeAdapter())
        }


    }

    inner class NodeBaseAdapter : BaseNodeProvider() {
        override val itemViewType: Int get() = 0
        override val layoutId: Int get() = R.layout.item_bill_list_base

        override fun convert(helper: BaseViewHolder, item: BaseNode) {
            var bill = item as Bill

            var tvDate = helper.getView<TextView>(R.id.tv_bill_list_date)
            val params = tvDate.layoutParams as ViewGroup.MarginLayoutParams
            if (mType == BillType.UNPAID_BILL) {
                helper.getView<ImageView>(R.id.iv_bill_list_radio_all).visibility = View.VISIBLE
                params.leftMargin = UIUtil.dip2px(context, 8.0)
            } else {
                helper.getView<ImageView>(R.id.iv_bill_list_radio_all).visibility = View.GONE
                params.leftMargin = UIUtil.dip2px(context, 16.0)
            }
            helper.setText(R.id.tv_bill_list_date, bill.predictDate)
            helper.setText(R.id.tv_bill_list_month, bill.predictDate.split("-")[1] + "月")

            var money = 0.0
            for (bill1 in bill.balanceInfoList) {
                money += (bill1 as Bill1).money.toDouble()
            }
            helper.setText(R.id.tv_bill_list_total_money, "$money 元")


            helper.setBackgroundColor(
                R.id.ll_bill_list_top,
                if (bill.isExpanded) resources.getColor(R.color.color_3D1273f7) else resources.getColor(
                    R.color.white
                )
            )
            helper.getView<TextView>(R.id.tv_bill_list_total_money)
                .setDrawRight(if (bill.isExpanded) R.mipmap.up_triangle_sel else R.mipmap.down_triangle)
            var radioAll = helper.getView<ImageView>(R.id.iv_bill_list_radio_all)
            radioAll.setOnClickListener {
                bill.isSelect = !bill.isSelect
                for (bill1 in bill.balanceInfoList) {
                    (bill1 as Bill1).isSelect = bill.isSelect
                }
                getAdapter()!!.notifyItemChanged(helper.absoluteAdapterPosition)
                mNodeAdapter!!.getAdapter()!!.notifyDataSetChanged()
                calculationTotalMoney()
            }
            var count = 0
            for (bill1 in bill.balanceInfoList) {
                if ((bill1 as Bill1).isSelect) {
                    count++
                }
            }
            bill.isSelect = count == bill.balanceInfoList.size
            radioAll.setImageResource(if (bill.isSelect) R.mipmap.radio_select else R.drawable.radio_no_select)

            var sl_bottom = helper.getView<ShadowLayout>(R.id.sl_bottom)
            sl_bottom.visibility = if (bill.isExpanded) View.GONE else View.VISIBLE

        }

        override fun onClick(helper: BaseViewHolder, view: View, data: BaseNode, position: Int) {
            getAdapter()!!.expandOrCollapse(position)
        }

    }

    inner class NodeAdapter : BaseNodeProvider() {
        override val itemViewType: Int get() = 1
        override val layoutId: Int get() = R.layout.item_bill_list_node

        override fun convert(helper: BaseViewHolder, item: BaseNode) {
            var bill1 = item as Bill1

            var tvType = helper.getView<TextView>(R.id.tv_bill_list_type)
            val params = tvType.layoutParams as ViewGroup.MarginLayoutParams
            if (mType == BillType.UNPAID_BILL) {
                helper.getView<ImageView>(R.id.iv_bill_list_radio).visibility = View.VISIBLE
                params.leftMargin = UIUtil.dip2px(context, 8.0)
            } else {
                helper.getView<ImageView>(R.id.iv_bill_list_radio).visibility = View.GONE
                params.leftMargin = UIUtil.dip2px(context, 16.0)
            }


            helper.setText(R.id.tv_bill_list_type, bill1.typeIdName)
            helper.setText(R.id.tv_bill_list_money, bill1.money + "元")
            helper.setText(R.id.tv_bill_list_due_date, bill1.predictDate)
            var begin =
                bill1.beginDate.substring(bill1.beginDate.indexOf("-") + 1).replace("-", ".")
            var end = bill1.endDate.substring(bill1.endDate.indexOf("-") + 1).replace("-", ".")
            helper.setText(R.id.tv_bill_list_month_range, "$begin—$end")
            var raio = helper.getView<ImageView>(R.id.iv_bill_list_radio)
            raio.setImageResource(if (bill1.isSelect) R.mipmap.radio_select else R.drawable.radio_no_select)
            raio.setOnClickListener {
                bill1.isSelect = !bill1.isSelect
                getAdapter()!!.notifyItemChanged(helper.absoluteAdapterPosition)
                mNodeBaseAdapter!!.getAdapter()!!.notifyDataSetChanged()
                calculationTotalMoney()
            }

            helper.getView<View>(R.id.view_bottom_line).visibility = bill1.isVisibleLine
            helper.getView<ShadowLayout>(R.id.sl_content)
                .setShadowHiddenBottom(bill1.isVisibleLine == View.VISIBLE)
            (helper.getView<View>(R.id.tv_bill_list_due_date).layoutParams as ViewGroup.MarginLayoutParams).bottomMargin =
                if (bill1.isVisibleLine == View.VISIBLE) UIUtil.dip2px(
                    context,
                    12.0
                ) else UIUtil.dip2px(context, 20.0)

//             (helper.getView<ConstraintLayout>(R.id.cl_bill_list_item).layoutParams as ViewGroup.MarginLayoutParams).bottomMargin =
//                                if (bill1.isVisibleLine == View.VISIBLE) UIUtil.dip2px(context, 0.0) else UIUtil.dip2px(context, 20.0)


//            Log.e("--------------父position", getAdapter()!!.findParentNode(helper.absoluteAdapterPosition).toString())
//            Log.e("--------------子position", helper.absoluteAdapterPosition.toString())
//            Log.e("--------------layout Position Position", helper.layoutPosition.toString())
//            Log.e("--------------data.size", getAdapter()!!.data.size.toString())
//            Log.e("--------------balance Info List.size", (getAdapter()!!.data as MutableList<Bill>).size.toString())

        }

    }

    /**
     * 处理数据
     */
    private fun processingData(list: MutableList<BillData>) {
        mData.clear()
        var billList: MutableList<Bill> = mutableListOf()
        for (billData in list) {
            var bill1List = mutableListOf<BaseNode>()
            for (baseNode in billData.balanceInfoList) {
                bill1List.add(baseNode)
            }
            (bill1List[bill1List.size - 1] as Bill1).isVisibleLine = View.GONE
            var bill = Bill(billData.predictDate, bill1List)
            billList.add(bill)
        }

        mData.addAll(billList)
        mDeptListShowAdapter!!.setList(mData)
        mDeptListShowAdapter!!.notifyDataSetChanged()
        mNodeBaseAdapter!!.getAdapter()!!.notifyDataSetChanged()
        if (mData.size == 0) {
            mView.statusView.showEmpty()
        } else {
            mView.statusView.showContent()
        }
    }

    /**
     * 重置金额
     */
    private fun resetTotalMoney() {
        mTotalMoney = 0.0
        mView.tvTotalMoney.text = "合计：$mTotalMoney 元"
    }

    /**
     * 计算选中金额
     */
    private fun calculationTotalMoney() {
        var totalMoney = 0.0
        for (bill in mData) {
            for (bill1 in bill.balanceInfoList) {
                var b1 = bill1 as Bill1
                if (b1.isSelect) {
                    totalMoney += b1.money.toDouble()
                }
            }
        }
        mTotalMoney = totalMoney
        mView.tvTotalMoney.text = "合计：$mTotalMoney 元"

    }

    /**
     * 支付
     */
    private fun pay() {
        toast(mTotalMoney.toString() + "元")
        var ids = ""
        var moneys = ""
        for (bill in mData) {
            for (bill1 in bill.balanceInfoList) {
                var b1 = bill1 as Bill1
                if (b1.isSelect) {
                    ids += b1.id + ","
                    moneys += b1.money + ","
                }
            }
        }

    }

}